﻿using Corina.Commands;
using Corina.Common;
using Corina.Datamodel.DataObject;
using Corina.Datamodel.Entities;
using Corina.Enumerations;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Input;

namespace Corina.Cydee.Apphub.Viewmodels
{
    public class DeviceViewmodel : ViewmodelBase
    {
        #region Constructor
        public DeviceViewmodel()
        {
            DeviceClient.GetDeviceItemsCompleted += GetDeviceItemsCompleted;
            DeviceClient.GetAllDeviceDataTransferTypeItemsCompleted += GetAllTransferCompleted;
            DeviceClient.GetDeviceKindItemsCompleted += GetDeviceKindItemsCompleted;
            DeviceClient.InsertDeviceCompleted+=InsertDeviceCompleted;
            if (DataContext.IsValid)
            {
                LoadData();
            }
        }

        #endregion

        #region Methods

        private void InsertDeviceCompleted(object sender, DataService.InsertDeviceCompletedEventArgs e)
        {
            SelectedDataModule = null;
            SelectedDeviceKind = null;
            Operation = EntityOperation.None;
            LoadData();
        }

        private void GetDeviceKindItemsCompleted(object sender, DataService.GetDeviceKindItemsCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                DeviceKindCollection = new ObservableCollection<DeviceKindInfo>(e.Result.Entities.OfType<DeviceKindInfo>());
            }
        }

        private void GetAllTransferCompleted(object sender, DataService.GetAllDeviceDataTransferTypeItemsCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                DeviceDataTransferCollection = new ObservableCollection<DeviceDataTransferTypeInfo>(e.Result.Entities.OfType<DeviceDataTransferTypeInfo>());
            }
        }

        private void GetDeviceItemsCompleted(object sender, DataService.GetDeviceItemsCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                ItemsCollection = new ObservableCollection<DataObjectInfo>(e.Result.DataObjects);
            }
            else
            {
                MessageBox.Show(e.Error.Message);
            }
            IsBusy = false;
        }

        private void LoadRelatedData()
        {
            if (DeviceKindCollection.IsNullOrEmpty())
            {
                DeviceClient.GetDeviceKindItemsAsync();
            }

            if (DeviceDataTransferCollection.IsNullOrEmpty())
            {
                DeviceClient.GetAllDeviceDataTransferTypeItemsAsync(Account, Password);
            }
        }

        protected override void LoadData(params object[] paras)
        {
            IsBusy = true;
            DeviceClient.GetDeviceItemsAsync(0, "", 0, Index, 20);
        } 
        #endregion

        #region Collection
        private ObservableCollection<DeviceKindInfo> _deviceKindCollection;
        public ObservableCollection<DeviceKindInfo> DeviceKindCollection
        {
            get { return _deviceKindCollection; }
            set
            {
                _deviceKindCollection = value;
                RaisePropertyChanged(() => DeviceKindCollection);
            }
        }

        private ObservableCollection<DeviceDataTransferTypeInfo> _deviceDataTransferCollection;
        public ObservableCollection<DeviceDataTransferTypeInfo> DeviceDataTransferCollection
        {
            get { return _deviceDataTransferCollection; }
            set
            {
                _deviceDataTransferCollection = value;
                RaisePropertyChanged(() => DeviceDataTransferCollection);
            }
        }

        private ObservableCollection<DataObjectInfo> _itemsCollection;
        public ObservableCollection<DataObjectInfo> ItemsCollection
        {
            get { return _itemsCollection; }
            set
            {
                _itemsCollection = value;
                RaisePropertyChanged(() => ItemsCollection);
                RaisePropertyChanged(() => DisplayCollection);
            }
        }

        private string _keywords = string.Empty;
        public string Keywords
        {
            get { return _keywords; }
            set
            {
                _keywords = value;
                RaisePropertyChanged(() => Keywords);
                RaisePropertyChanged(() => DisplayCollection);
            }
        }

        public IEnumerable<object> DisplayCollection
        {
            get
            {
                if(ItemsCollection == null)
                {
                    return null;
                }

                var items = (from t in ItemsCollection
                             select new
                             {
                                 Id = t["Id"],
                                 DeviceSn = (string)t["DeviceSn"],
                                 Kind = (string)t["Kind"],
                                 DataModule = (string)t["DataModule"],
                                 ManufactureDate = (DateTime)t["ManufactureDate"],
                                 RatePrice = t["RatePrice"]
                             }).Where(t => t.DeviceSn.Contains(Keywords) || t.Kind.Contains(Keywords) || t.DataModule.Contains(Keywords));
                return items;
            }
        }
        #endregion

        #region Properties

        private DeviceInfo _updateEntity = new DeviceInfo();
        public DeviceInfo UpdateEntity
        {
            get { return _updateEntity; }
            set
            {
                _updateEntity = value;
                RaisePropertyChanged(() => UpdateEntity);
            }
        }

        public DateTime ValidDate
        {
            get { return DateTime.Now; }
        }
        #endregion

        #region Update
        private DeviceKindInfo _selectedDeviceKind;
        public DeviceKindInfo SelectedDeviceKind
        {
            get { return _selectedDeviceKind; }
            set
            {
                _selectedDeviceKind = value;
                RaisePropertyChanged(() => SelectedDeviceKind);
                if (SelectedDeviceKind != null)
                {
                    UpdateEntity.DeviceKindId = SelectedDeviceKind.Id;
                }
            }
        }

        private DeviceDataTransferTypeInfo _selectedDataModule;
        public DeviceDataTransferTypeInfo SelectedDataModule
        {
            get { return _selectedDataModule; }
            set
            {
                _selectedDataModule = value;
                RaisePropertyChanged(() => SelectedDataModule);
                if (SelectedDataModule != null)
                {
                    UpdateEntity.DataTransferTypeId = SelectedDataModule.Id;
                }
            }
        }
        #endregion

        #region Command
        public ICommand InsertCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate
                    {
                        UpdateEntity = new DeviceInfo();
                        Operation = EntityOperation.Insert;
                        LoadRelatedData();
                    }
                };
            }
        }

        public ICommand RemoveCommand
        {
            get
            {
                return new DelegateCommand(t =>
                {
                    int id = Convert.ToInt32(t);

                    if (ShowConfirm(Language.LanguageKeys.IDS_DELETE_CONFIRM) == MessageBoxResult.OK)
                    {
                        DeviceClient.RemoveDeviceAsync(Account, Password, id);
                    }
                });
            }
        }

        public ICommand SubmitCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate
                    {
                        DeviceClient.InsertDeviceAsync(Account, Password, UpdateEntity.DeviceKindId, UpdateEntity.DeviceSn, UpdateEntity.ManufactureDate, UpdateEntity.RatePrice, UpdateEntity.DataTransferTypeId);
                    }
                };
            }
        }

        public ICommand CancelCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate {
                        SelectedDataModule = null;
                        SelectedDeviceKind = null;
                        UpdateEntity = new DeviceInfo();
                        Operation = EntityOperation.None;
                    }
                };
            }
        }
        #endregion
    }
}
